package com.changan.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.changan.entity.User;
import com.changan.mapper.UserMapper;
import com.changan.utils.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserMapper userMapper;

    /**
     * 预处理
     *
     * @param request  current HTTP request
     * @param response current HTTP response
     * @param handler  chosen handler to execute, for type and/or instance evaluation
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=UTF-8");

        // 放行预请求
        if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
            return true;
        }

        // 1. 从请求头中获取Authorization（格式：Bearer token）
        String authorization = request.getHeader("Authorization");
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            // 无有效Token，返回401未授权
            response.setStatus(401);
            response.getWriter().write("请先登录");
            return false;
        }

        // 2. 提取Token（去除"Bearer "前缀）
        String token = authorization.substring(7);

        boolean expire = JWTUtils.isExpire(token);
        if (expire) {
            // Token已过期，返回401未授权
            response.setStatus(401);
            response.getWriter().write("Token已过期");
            return false;
        }

        String username = JWTUtils.getUsername(token);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(username), User::getUsername, username);
        User user = userMapper.selectOne(wrapper);
        if (!JWTUtils.verify(token, username, user.getPassword())) {
            // Token无效，返回401未授权
            response.setStatus(401);
            response.getWriter().write("Token无效");
            return false;
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
